package com.jsh.erp.service.material;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Sets;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.Replenishment;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.attachment.AttachmentService;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.materialCategory.MaterialCategoryService;
import com.jsh.erp.service.materialExtend.MaterialExtendService;
import com.jsh.erp.service.msg.MsgService;
import com.jsh.erp.service.person.PersonService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.unit.UnitService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.*;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaterialService {
    private Logger logger = LoggerFactory.getLogger(MaterialService.class);

    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private MaterialExtendMapper materialExtendMapper;
    @Resource
    private MaterialMapperEx materialMapperEx;
    @Resource
    private MaterialCategoryMapperEx materialCategoryMapperEx;
    @Resource
    private MaterialExtendMapperEx materialExtendMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private DepotItemMapperEx depotItemMapperEx;
    @Resource
    private DepotItemService depotItemService;
    @Resource
    private MaterialCategoryService materialCategoryService;
    @Resource
    private UnitService unitService;
    @Resource
    private MaterialInitialStockMapper materialInitialStockMapper;
    @Resource
    private MaterialInitialStockMapperEx materialInitialStockMapperEx;
    @Resource
    private MaterialCurrentStockMapper materialCurrentStockMapper;
    @Resource
    private MaterialCurrentStockMapperEx materialCurrentStockMapperEx;
    @Resource
    private DepotService depotService;
    @Resource
    private MaterialExtendService materialExtendService;
    @Resource
    private RedisService redisService;
    @Resource
    private AttachmentService  attachmentService;
    @Resource
    private UnitMapper unitMapper;
    @Resource
    private SupplierService supplierService;
    @Resource
    private MsgMapper msgMapper;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private SynchronizationTaskMapperEx synchronizationTaskMapperEx;
    @Resource
    private CashBoxRecordMapper cashBoxRecordMapper;
    @Resource
    private CashBoxRecordMapperEx cashBoxRecordMapperEx;
    @Resource
    private PersonService personService;
    @Resource
    private PersonMapper personMapper;

    public Material getMaterial(String id)throws Exception {
        Material result=null;
        try{
            result=materialMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<Material> getMaterialListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<Material> list = new ArrayList<>();
        try{
            MaterialExample example = new MaterialExample();
            example.createCriteria().andIdIn(idList);
            list = materialMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Material> getMaterial() throws Exception{
        MaterialExample example = new MaterialExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Material> list=null;
        try{
            list=materialMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<MaterialVo4Unit> select(String materialParam, String color, String weight, String expiryNum,
                                        String enableSerialNumber, String enableBatchNumber, String enabled,
                                        String remark, String categoryId, String mpList, int offset, int rows,
                                        String name, String standard, String model, String barCode)
            throws Exception{
        String[] mpArr = new String[]{};
        if(StringUtil.isNotEmpty(mpList)){
            mpArr= mpList.split(",");
        }
        List<MaterialVo4Unit> resList = new ArrayList<>();
        List<MaterialVo4Unit> list =null;
        try{
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = getListByParentId(categoryId);
            }
            list= materialMapperEx.selectByConditionMaterial(materialParam, color, weight, expiryNum,
                    enableSerialNumber, enableBatchNumber, enabled, remark, idList, mpList, offset, rows,
                    name,standard,model,barCode);
            if (null != list && list.size()>0) {
                Map<String,BigDecimal> currentStockMap = getCurrentStockMapByMaterialList(list,null);
                for (MaterialVo4Unit m : list) {
                    m.setMaterialOther(getMaterialOtherByParam(mpArr, m));
                    BigDecimal stock = currentStockMap.get(m.getId())!=null? currentStockMap.get(m.getId()): BigDecimal.ZERO;
                    m.setStock(stock);
                    StringBuffer str = new StringBuffer();
//                    if (StringUtils.isNotEmpty(m.getUnitId())){
//                        Unit unit =  unitService.getUnit(m.getUnitId());
//                        if(null!= unit.getOtherUnit() && StringUtils.isNotEmpty(unit.getOtherUnit()) && null!= unit.getRatio() && unit.getRatio() != 0) {
//                            str.append("(" +stock.divide(BigDecimal.valueOf(unit.getRatio()),2,BigDecimal.ROUND_HALF_UP)+unit.getOtherUnit()+")");
//                        }
//                        if (null!= unit.getOtherUnitTwo() && StringUtils.isNotEmpty(unit.getOtherUnitTwo()) && null!= unit.getRatioTwo() && unit.getRatioTwo() != 0) {
//                            str.append("/(" +stock.divide(BigDecimal.valueOf(unit.getRatioTwo()),2,BigDecimal.ROUND_HALF_UP)+unit.getOtherUnitTwo()+")");
//                        }
//                    }
                    m.setAssistStock(str.toString());
                    resList.add(m);
                }
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public Long countMaterial(String materialParam, String color, String weight, String expiryNum,
                              String enableSerialNumber, String enableBatchNumber, String enabled,
                              String remark, String categoryId,String mpList,
                              String name, String standard, String model, String barCode)throws Exception {
        Long result =null;
        try{
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = getListByParentId(categoryId);
            }
            result= materialMapperEx.countsByMaterial(materialParam, color, weight, expiryNum,
                    enableSerialNumber, enableBatchNumber, enabled, remark, idList, mpList,
                    name,standard,model,barCode);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertMaterial(JSONObject obj, HttpServletRequest request)throws Exception {
        Material m = JSONObject.parseObject(obj.toJSONString(), Material.class);
        m.setEnabled(true);
        try{
            if (StringUtils.isNotEmpty(m.getCategoryId())){
                boolean b = materialCategoryService.checkCategoryIdIsParents(m.getCategoryId());
                if (!b){
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_IS_PARENT_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_CATEGORY_IS_PARENT_MSG : ExceptionConstants.MATERIAL_CATEGORY_IS_PARENT_MSG_US);
                }
            }
            m.setUploadFlag("0");
            materialMapperEx.insertSelectiveEx(m);
            String mId = m.getId();
            materialExtendService.saveDetials(obj, obj.getString("sortList"), mId, "insert");
//            /**处理文件**/
            attachmentService.saveMaterialAttachment(obj,mId,request);
            if(obj.get("stock")!=null) {
                JSONArray stockArr = obj.getJSONArray("stock");
                for (int i = 0; i < stockArr.size(); i++) {
                    JSONObject jsonObj = stockArr.getJSONObject(i);
                    if(jsonObj.get("id")!=null && jsonObj.get("initStock")!=null) {
                        String number = jsonObj.getString("initStock");
                        BigDecimal lowSafeStock = null;
                        BigDecimal highSafeStock = null;
                        if(jsonObj.get("lowSafeStock")!=null) {
                            lowSafeStock = jsonObj.getBigDecimal("lowSafeStock");
                        }
                        if(jsonObj.get("highSafeStock")!=null) {
                            highSafeStock = jsonObj.getBigDecimal("highSafeStock");
                        }
                        String depotId = jsonObj.getString("id");
                        if(StringUtil.isNotEmpty(number) && Double.parseDouble(number)>0 || lowSafeStock!=null || highSafeStock!=null) {
                            insertInitialStockByMaterialAndDepot(depotId, mId, parseBigDecimalEx(number), lowSafeStock, highSafeStock);
                            insertCurrentStockByMaterialAndDepot(depotId, mId, parseBigDecimalEx(number));
                        }
                    }
                }
            }
            logService.insertLog("商品",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(m.getName()).toString(), request);
            return 1;
        }
        catch (BusinessRunTimeException ex) {
            throw new BusinessRunTimeException(ex.getCode(), ex.getMessage());
        }
        catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
            return 0;
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateMaterial(JSONObject obj, HttpServletRequest request) throws Exception{
        Material material = JSONObject.parseObject(obj.toJSONString(), Material.class);
        try{
            material.setUploadFlag("0");
            material.setUpdateTime(new Date());
            materialMapper.updateByPrimaryKeySelective(material);
            if(material.getUnitId() == null) {
                materialMapperEx.setUnitIdToNull(material.getId());
            }
            if(material.getExpiryNum() == null) {
                materialMapperEx.setExpiryNumToNull(material.getId());
            }
            materialExtendService.saveDetials(obj, obj.getString("sortList"),material.getId(), "update");
//            /**处理文件**/
            attachmentService.saveMaterialAttachment(obj,material.getId(),request);
            if(obj.get("stock")!=null) {
                JSONArray stockArr = obj.getJSONArray("stock");
                for (int i = 0; i < stockArr.size(); i++) {
                    JSONObject jsonObj = stockArr.getJSONObject(i);
                    if (jsonObj.get("id") != null && jsonObj.get("initStock") != null) {
                        String number = jsonObj.getString("initStock");
                        BigDecimal lowSafeStock = null;
                        BigDecimal highSafeStock = null;
                        if(jsonObj.get("lowSafeStock")!=null) {
                            lowSafeStock = jsonObj.getBigDecimal("lowSafeStock");
                        }
                        if(jsonObj.get("highSafeStock")!=null) {
                            highSafeStock = jsonObj.getBigDecimal("highSafeStock");
                        }
                        String depotId = jsonObj.getString("id");
                        //初始库存-先清除再插入
                        materialInitialStockMapperEx.deleteByMaterialId(material.getId(),depotId);
                        if (StringUtil.isNotEmpty(number) || lowSafeStock!=null || highSafeStock!=null) {
                            insertInitialStockByMaterialAndDepot(depotId, material.getId(), parseBigDecimalEx(number), lowSafeStock, highSafeStock);
                        }
                        //更新当前库存
                        depotItemService.updateCurrentStockFun(material.getId(), depotId);
                    }
                }
            }
            logService.insertLog("商品",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(material.getName()).toString(), request);
            return 1;
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
            return 0;
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteMaterial(String id, HttpServletRequest request)throws Exception {
        return batchDeleteMaterialByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteMaterial(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteMaterialByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteMaterialByIds(String ids) throws Exception{
        String [] idArray=ids.split(",");
        //校验单据子表	jsh_depot_item
        List<DepotItem> depotItemList =null;
        try{
            depotItemList=  depotItemMapperEx.getDepotItemListListByMaterialIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if(depotItemList!=null&&depotItemList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,MaterialIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,"zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US);
        }
        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Material> list = getMaterialListByIds(ids);
        for(Material material: list){
            sb.append("[").append(material.getName()).append("]");
        }
        logService.insertLog("商品", sb.toString(),StringUtil.getRequest());
        User userInfo=userService.getCurrentUser();
        //校验通过执行删除操作
        try{
            //逻辑删除商品
            materialMapperEx.batchDeleteMaterialByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
            //逻辑删除商品价格扩展
            materialExtendMapperEx.batchDeleteMaterialExtendByMIds(idArray);
            return 1;
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
            return 0;
        }
    }

     public int checkIsNameExist(String id, String name) throws Exception{
        MaterialExample example = new MaterialExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Material> list =null;
        try{
            list=  materialMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }

    public int checkIsExist(String id, String name, String model, String color, String standard, String mfrs,
                            String otherField1, String otherField2, String otherField3, String unit, String unitId)throws Exception {
        return materialMapperEx.checkIsExist(id, name, model, color, standard, mfrs, otherField1,
                otherField2, otherField3, unit, unitId);
    }
    public int checkMaterialNameIsExist(String name,String id,String standard)throws Exception {
        MaterialExample example = new MaterialExample();
        MaterialExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(name);
        criteria.andStandardEqualTo(standard);
        if (!StringUtils.isEmpty(id) && !"0".equals(id)) {
            criteria.andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        } else {
            criteria.andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        }
        List<Material> list =null;
        try{
            list = materialMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("商品批量修改状态",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(ids).toString(),
                StringUtil.getRequest());
        List<String> materialIds = StringUtil.strToStringList(ids);
        if (!status){
            if (materialIds!=null && materialIds.size()>0){
                for (String materialId:materialIds){
//                    BigDecimal stockByParam = depotItemService.getStockByParam(null, materialId, null, null);
                    BigDecimal stockByParam =  getCurrentStockMapByMaterialId(materialId,null);
                    if (stockByParam !=null && stockByParam.compareTo(BigDecimal.ZERO)>0){
                        Material material = getMaterial(materialId);
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_EMPTY_CODE,
                                "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_STOCK_NOT_EMPTY_MSG : ExceptionConstants.MATERIAL_STOCK_NOT_EMPTY_MSG_US);
                    }
                }
            }
        }
        Material material = new Material();
        material.setEnabled(status);
        material.setUploadFlag("0");
        MaterialExample example = new MaterialExample();
        example.createCriteria().andIdIn(materialIds);
        int result =0;
        try{
            result=  materialMapper.updateByExampleSelective(material, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchUpdateSalesPrice(String enableBatchNumber, String ids)throws Exception {
//        logService.insertLog("商品批量确定售价",
//                BusinessConstants.LOG_OPERATION_TYPE_EDIT + ids,
//                StringUtil.getRequest());
        List<String> materialIds = StringUtil.strToStringList(ids);
        Material material = new Material();
        material.setEnableBatchNumber(enableBatchNumber);
        material.setUploadFlag("0");
        MaterialExample example = new MaterialExample();
        example.createCriteria().andIdIn(materialIds);
        int result =0;
        try{
            result=  materialMapper.updateByExampleSelective(material, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public Unit findUnit(String mId)throws Exception{
        Unit unit = new Unit();
        try{
            List<Unit> list = materialMapperEx.findUnitList(mId);
            if(list!=null && list.size()>0) {
                unit = list.get(0);
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return unit;
    }

    public List<MaterialVo4Unit> findById(String id)throws Exception{
        List<MaterialVo4Unit> list =null;
        try{
            list=  materialMapperEx.findById(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<MaterialVo4Unit> findByIdWithMeId(String meId)throws Exception{
        List<MaterialVo4Unit> list =null;
        try{
            list=  materialMapperEx.findByIdWithMeId(meId);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<String> getListByParentId(String parentId) {
        List<String> idList = new ArrayList<String>();
        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
        idList.add(parentId);
        if(list!=null && list.size()>0) {
            getIdListByParentId(idList, parentId);
        }
        return idList;
    }

    public List<String> getIdListByParentId(List<String> idList, String parentId){
        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
        if(list!=null && list.size()>0) {
            for(MaterialCategory mc : list){
                idList.add(mc.getId());
                getIdListByParentId(idList, mc.getId());
            }
        }
        return idList;
    }

    public List<MaterialVo4Unit> findBySelectWithBarCode(String categoryId, String q, String enableSerialNumber,
                                                         String enableBatchNumber, Integer offset, Integer rows,
                                                         String organId,String color)throws Exception{
        List<MaterialVo4Unit> list =null;
        try{
            List<String> idList = new ArrayList<>();
            if(categoryId!=null){
                idList = getListByParentId(categoryId);
            }
            if(StringUtil.isNotEmpty(q)) {
                q = q.replace("'", "");
                q = q.replace(" ", "%");
                q = q.trim();
            }
            list=  materialMapperEx.findBySelectWithBarCode(idList, q, enableSerialNumber, enableBatchNumber, offset, rows,organId,
                    color);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int findBySelectWithBarCodeCount(String categoryId, String q, String enableSerialNumber,
                                            String enableBatchNumber,String organId,String color)throws Exception{
        int result=0;
        try{
            List<String> idList = new ArrayList<>();
            if(categoryId!=null){
                idList = getListByParentId(categoryId);
            }
            if(StringUtil.isNotEmpty(q)) {
                q = q.replace("'", "");
            }
            result = materialMapperEx.findBySelectWithBarCodeCount(idList, q, enableSerialNumber, enableBatchNumber,organId,
                    color);
        }catch(Exception e){
            logger.error("异常码[{}],异常提示[{}],异常[{}]",
                    ExceptionConstants.DATA_READ_FAIL_CODE,"zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_READ_FAIL_MSG : ExceptionConstants.DATA_READ_FAIL_MSG_US,e);
            throw new BusinessRunTimeException(ExceptionConstants.DATA_READ_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_READ_FAIL_MSG : ExceptionConstants.DATA_READ_FAIL_MSG_US);
        }
        return result;
    }

    public List<MaterialVo4Unit> exportExcel( String name,
                                              String barCode,
                                              String standard,
                                              String model,
                                              String color, String expiryNum, String enabled,
                                             String enableSerialNumber, String enableBatchNumber, String remark, String categoryId,List<String> materialIdArr)throws Exception {
        List<MaterialVo4Unit> resList = new ArrayList<>();
        List<MaterialVo4Unit> list =null;
        try{
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = getListByParentId(categoryId);
            }
            list=  materialMapperEx.exportExcel(name,barCode,standard,model,color,  expiryNum, enabled, enableSerialNumber,
                    enableBatchNumber, remark, idList,materialIdArr);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (null != list) {
            resList.addAll(list);
        }
        return resList;
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BaseResponseInfo importExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        BaseResponseInfo info = new BaseResponseInfo();
        MaterialExample example = new MaterialExample();
        example.createCriteria();
        MaterialExample example1 = new MaterialExample();
        example1.createCriteria();
        try {
            long beginTime = System.currentTimeMillis();
            //文件扩展名只能为xls
            String fileName = file.getOriginalFilename();
            if(StringUtil.isNotEmpty(fileName)) {
                String fileExt = fileName.substring(fileName.indexOf(".")+1);
                if(!"xls".equals(fileExt)) {
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXTENSION_ERROR_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_EXTENSION_ERROR_MSG : ExceptionConstants.MATERIAL_EXTENSION_ERROR_MSG_US);
                }
            }
            Workbook workbook = Workbook.getWorkbook(file.getInputStream());
            User user = userService.getCurrentUser();
            Sheet[] sheets = workbook.getSheets();
//            List<Material> insertList=new ArrayList<Material>();
//            List<Material> updateList=new ArrayList<Material>();
//            List<MaterialExtend> extendInsertList=new ArrayList<MaterialExtend>();
//            List<MaterialExtend> extendUpdateList=new ArrayList<MaterialExtend>();
            for (int y=0; y < sheets.length; y++) {
                Sheet src=sheets[y];
                List<MaterialWithInitStock> mList = new ArrayList<>();
                String sheetName = src.getName();
                String parentId=null;
                if (StringUtil.isEmpty(sheetName)) {
                    throw new BusinessRunTimeException(ExceptionConstants.SHEET_NAME_EMPTY_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.SHEET_NAME_EMPTY_MSG : ExceptionConstants.SHEET_NAME_EMPTY_MSG_US);

                }else {
                    parentId = materialCategoryService.getCategoryIdByName(sheetName);
                    if (StringUtils.isEmpty(parentId)) {
                        throw new BusinessRunTimeException(ExceptionConstants.SHEET_ID_EMPTY_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.SHEET_ID_EMPTY_MSG : ExceptionConstants.SHEET_ID_EMPTY_MSG_US, sheetName));
                    }
                }
                for (int i = 1; i < src.getRows(); i++) {
                    String color = ExcelUtils.getContent(src, i, 0); //关联码
                    String categoryName = ExcelUtils.getContent(src, i, 1); //类别
                    String name = ExcelUtils.getContent(src, i, 2); //名称
                    String standard = ExcelUtils.getContent(src, i, 3); //规格
                    String supplier = ExcelUtils.getContent(src, i, 4); //供应商
                    String unit = ExcelUtils.getContent(src, i, 5); //基本单位
                    //名称为空
                    if(StringUtil.isEmpty(name)) {
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_EMPTY_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NAME_EMPTY_MSG : ExceptionConstants.MATERIAL_NAME_EMPTY_MSG_US, "("+sheetName+")"+(i+1)));
                    }
                    //基本单位为空
                    if(StringUtil.isEmpty(unit)) {
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_EMPTY_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_UNIT_EMPTY_MSG : ExceptionConstants.MATERIAL_UNIT_EMPTY_MSG_US,"("+sheetName+")"+(i+1)));
                    }
                    MaterialWithInitStock m = new MaterialWithInitStock();
                    m.setColor(color);
                    m.setName(name);
                    m.setStandard(standard);
                    String categoryId = materialCategoryService.getCategoryIdByParentName(categoryName,parentId);
                    if(!StringUtils.isEmpty(categoryId)){
                        m.setCategoryId(categoryId);
                    }else {
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_EMPTY_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_CATEGORY_ID_EMPTY_MSG : ExceptionConstants.MATERIAL_CATEGORY_ID_EMPTY_MSG_US,"("+sheetName+")"+(i+1)));

                    }
                    String organId = supplierService.getSupplierByName(supplier);
                    if(!StringUtils.isEmpty(organId)){
                        m.setOrganId(organId);
                    }
                    String barCode = ExcelUtils.getContent(src, i, 6); //基础条码
                    String code = ExcelUtils.getContent(src, i, 7); //基础编号
                    String ratio = ExcelUtils.getContent(src, i, 8); //比例
                    String purchaseDecimal = ExcelUtils.getContent(src, i, 9); //采购价
                    String commodityDecimal = ExcelUtils.getContent(src, i, 10); //零售价
                    String wholesaleDecimal = ExcelUtils.getContent(src, i, 11); //销售价/一级批发价
                    String mfrs = ExcelUtils.getContent(src, i, 12); //是否称重
                    String enabled = ExcelUtils.getContent(src, i, 13); //状态
                    //状态格式错误
                    if(!"1".equals(enabled) && !"0".equals(enabled)) {
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_ENABLED_ERROR_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_ENABLED_ERROR_MSG : ExceptionConstants.MATERIAL_ENABLED_ERROR_MSG_US, "("+sheetName+")"+(i+1)));
                    }
                    if(!"1".equals(mfrs) && !"0".equals(mfrs)) {
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CODE_ERROR_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_CODE_ERROR_MSG : ExceptionConstants.MATERIAL_CODE_ERROR_MSG_US, "("+sheetName+")"+(i+1)));
                    }
                    if (StringUtil.isEmpty(ratio)){
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_RATIO_EMPTY_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_RATIO_EMPTY_MSG : ExceptionConstants.MATERIAL_RATIO_EMPTY_MSG_US, "("+sheetName+")"+(i+1)));

                    }else {
                        if( !StringUtil.isPositiveLong(ratio.trim())) {
                            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_RATIO_NOT_INTEGER_CODE,
                                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_RATIO_NOT_INTEGER_MSG : ExceptionConstants.MATERIAL_RATIO_NOT_INTEGER_MSG_US, "("+sheetName+")"+(i+1)));
                        }
                    }

                    if (StringUtil.isNotEmpty(purchaseDecimal)){
                        purchaseDecimal=purchaseDecimal.replace(",","");
                    }
                    if (StringUtil.isNotEmpty(commodityDecimal)){
                        commodityDecimal=commodityDecimal.replace(",","");
                    }
                    if (StringUtil.isNotEmpty(wholesaleDecimal)){
                        wholesaleDecimal=wholesaleDecimal.replace(",","");
                    }
                    //副单位为空
//                if(StringUtil.isEmpty(manyUnit)) {
//                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_MANY_UNIT_EMPTY_CODE,
//                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_MANY_UNIT_EMPTY_MSG : ExceptionConstants.MATERIAL_MANY_UNIT_EMPTY_MSG_US, i+1));
//                }
                    JSONObject materialExObj = new JSONObject();
                    JSONObject basicObj = new JSONObject();
                    basicObj.put("barCode", barCode);
                    basicObj.put("code", code);
                    basicObj.put("proportion", ratio); //基础单位比例 1
                    basicObj.put("commodityUnit", unit);
                    basicObj.put("purchaseDecimal", purchaseDecimal);
                    basicObj.put("commodityDecimal", commodityDecimal);
                    basicObj.put("wholesaleDecimal", wholesaleDecimal);
                    materialExObj.put("basic", basicObj);

                    Unit unitVo = new Unit();
                    unitVo.setId(IdUtils.getUUID());
                    unitVo.setName(unit);
                    unitVo.setRatio(Integer.parseInt(ratio.trim()));
                    unitVo.setUploadFlag("0");
                    unitMapper.insertSelective(unitVo);
                    m.setUnitId(unitVo.getId());
                    m.setUnit(unit);
                    m.setMaterialExObj(materialExObj);
                    m.setEnabled("1".equals(enabled));
                    m.setMfrs(mfrs);
                    m.setEnableBatchNumber("0");
                    mList.add(m);
                }
                for(MaterialWithInitStock m: mList) {
                    String mId = null;
                    //判断该商品是否存在，如果不存在就新增，如果存在就更新
                    String basicBarCode = getBasicBarCode(m);
                    List<Material> materials = getMaterialListByParam(m.getName(),m.getStandard(),m.getModel(),m.getColor(),m.getUnit(),basicBarCode,m.getCategoryId());
                    m.setUploadFlag("0");
                    if(materials.size() == 0) {
                        m.setId(IdUtils.getUUID());
                        materialMapperEx.insertSelectiveEx(m);
//                        insertList.add(m);
                        mId = m.getId();
                    } else {
                        mId = materials.get(0).getId();
                        String materialJson = JSON.toJSONString(m);
                        Material material = JSONObject.parseObject(materialJson, Material.class);
                        material.setId(mId);
//                        updateList.add(material);
                        materialMapper.updateByPrimaryKeySelective(material);
                    }
                    //给商品新增或更新条码与价格相关信息
                    JSONObject materialExObj = m.getMaterialExObj();
//                    insertOrUpdateMaterialExtend(materialExObj, "basic", "1", mId, user);
                    String basicStr = materialExObj.getString("basic");
                    MaterialExtend materialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
                    materialExtend.setMaterialId(mId);
                    materialExtend.setDefaultFlag("1");
                    materialExtend.setCreateTime(new Date());
                    materialExtend.setUpdateTime(System.currentTimeMillis());
                    materialExtend.setCreateSerial(user.getLoginName());
                    materialExtend.setUpdateSerial(user.getLoginName());
                    materialExtend.setUploadFlag("0");
                    String meId = materialExtendService.selectIdByMaterialIdAndDefaultFlag(mId, "1");
                    if (StringUtils.isEmpty(meId)) {
                        materialExtend.setId(IdUtils.getUUID());
                        materialExtendMapper.insertSelective(materialExtend);
//                        extendInsertList.add(materialExtend);
                    } else {
                        materialExtend.setId(meId);
                        materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
//                        extendUpdateList.add(materialExtend);
                    }

//                insertOrUpdateMaterialExtend(materialExObj, "other", "0", mId, user);
                }
//                insertList.clear();
//                updateList.clear();
//                extendInsertList.clear();
//                extendUpdateList.clear();
            }
//            if (insertList.size()>0){
//                materialMapperEx.insertList(insertList);
//            }
//            if (updateList.size()>0){
//
//            }
//            if (extendInsertList.size()>0){
//                materialExtendMapperEx.extendInsertList(extendInsertList);
//            }
//            if (extendUpdateList.size()>0){
//
//            }
            Long endTime = System.currentTimeMillis();
            logger.info("导入耗时：{}", endTime-beginTime);
            info.code = 200;
            info.data = "导入成功";
        } catch (BusinessRunTimeException e) {
            info.code = e.getCode();
            info.data = e.getData().get("message");
        } catch (Exception e) {
            e.printStackTrace();
            info.code = 500;
            info.data = "导入失败";
        }
        return info;
    }
    private Map<String, String> parseDepotToMap(List<Depot> depotList) {
        Map<String, String> map = new HashMap<>();
        for(Depot depot: depotList) {
            map.put(depot.getName(), depot.getId());
        }
        return map;
    }

    /**
     * 缓存各个仓库的库存信息
     * @param src
     * @param depotCount
     * @param depotMap
     * @param i
     * @return
     * @throws Exception
     */
    private Map<String, BigDecimal> getStockMapCache(Sheet src, int depotCount, Map<String, String> depotMap, int i) throws Exception {
        Map<String, BigDecimal> stockMap = new HashMap<>();
        for(int j = 1; j<= depotCount; j++) {
            int col = 18+j;
            if(col < src.getColumns()){
                String depotName = ExcelUtils.getContent(src, 1, col); //获取仓库名称
                if(StringUtil.isNotEmpty(depotName)) {
                    String depotId = depotMap.get(depotName);
                    if(!StringUtil.isEmpty(depotId)){
                        String stockStr = ExcelUtils.getContent(src, i, col);
                        if(StringUtil.isNotEmpty(stockStr)) {
                            stockMap.put(depotId, parseBigDecimalEx(stockStr));
                        }
                    }
                }
            }
        }
        return stockMap;
    }

    /**
     * 给商品新增或更新条码与价格相关信息
     * @param materialExObj
     * @param type
     * @param defaultFlag
     * @param mId
     * @param user
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertOrUpdateMaterialExtend(JSONObject materialExObj, String type, String defaultFlag, String mId, User user) throws Exception {
        if(StringUtil.isExist(materialExObj.get(type))){
            String basicStr = materialExObj.getString(type);
            MaterialExtend materialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
            materialExtend.setMaterialId(mId);
            materialExtend.setDefaultFlag(defaultFlag);
            materialExtend.setCreateTime(new Date());
            materialExtend.setUpdateTime(System.currentTimeMillis());
            materialExtend.setCreateSerial(user.getLoginName());
            materialExtend.setUpdateSerial(user.getLoginName());
            materialExtend.setUploadFlag("0");
            String meId = materialExtendService.selectIdByMaterialIdAndDefaultFlag(mId, defaultFlag);
            if(StringUtils.isEmpty(meId)){
                materialExtend.setId(IdUtils.getUUID());
                materialExtendMapper.insertSelective(materialExtend);
            } else {
                materialExtend.setId(meId);
                materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
            }
        }
    }

    public String getBasicBarCode(MaterialWithInitStock m) {
        String barCode = "";
        JSONObject materialExObj = m.getMaterialExObj();
        if(StringUtil.isExist(materialExObj.get("basic"))) {
            String basicStr = materialExObj.getString("basic");
            MaterialExtend basicMaterialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
            barCode = basicMaterialExtend.getBarCode();
        }
        return barCode;
    }
    public String getBasicCode(MaterialWithInitStock m) {
        String code = "";
        JSONObject materialExObj = m.getMaterialExObj();
        if(StringUtil.isExist(materialExObj.get("basic"))) {
            String basicStr = materialExObj.getString("basic");
            MaterialExtend basicMaterialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
            code = basicMaterialExtend.getCode();
        }
        return code;
    }

    /**
     * 根据条件返回产品列表
     * @param name
     * @return
     */
    private List<Material> getMaterialListByParam(String name, String standard, String model, String color, String unit,String basicBarCode,String categoryId) throws Exception {
        List<Material> list = new ArrayList<>();
        //如果通过组合条件没有查到该商品，则通过条码再查一次
//        if (StringUtil.isNotEmpty(basicBarCode)){
//            String materialId = materialExtendService.getInfoByBarCode(basicBarCode,name);
//            if(StringUtils.isNotEmpty(materialId)) {
//                Material material = new Material();
//                material.setId(materialId);
//                list.add(material);
//            }
//        }else {
            MaterialExample example = new MaterialExample();
            MaterialExample.Criteria criteria = example.createCriteria();
            criteria.andNameEqualTo(name);
            if (StringUtil.isNotEmpty(model)) {
                criteria.andModelEqualTo(model);
            }
            if (StringUtil.isNotEmpty(color)) {
                criteria.andColorEqualTo(color);
            }
//            if (StringUtil.isNotEmpty(standard)) {
//                criteria.andStandardEqualTo(standard);
//            }
            if (StringUtil.isNotEmpty(categoryId)) {
                criteria.andCategoryIdEqualTo(categoryId);
            }
//            if (StringUtil.isNotEmpty(unit)) {
//                criteria.andUnitEqualTo(unit);
//            }
            criteria.andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = materialMapper.selectByExample(example);
//        }

        return list;
    }

    /**
     * 写入初始库存
     * @param depotId
     * @param mId
     * @param stock
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertInitialStockByMaterialAndDepot(String depotId, String mId, BigDecimal stock, BigDecimal lowSafeStock, BigDecimal highSafeStock){
        MaterialInitialStock materialInitialStock = new MaterialInitialStock();
        materialInitialStock.setId(IdUtils.getUUID());
        materialInitialStock.setDepotId(depotId);
        materialInitialStock.setMaterialId(mId);
        stock = stock == null? BigDecimal.ZERO: stock;
        materialInitialStock.setNumber(stock);
        if(lowSafeStock!=null) {
            materialInitialStock.setLowSafeStock(lowSafeStock);
        }
        if(highSafeStock!=null) {
            materialInitialStock.setHighSafeStock(highSafeStock);
        }
        materialInitialStock.setUploadFlag("0");
        materialInitialStockMapper.insertSelective(materialInitialStock); //存入初始库存
    }

    /**
     * 写入当前库存
     * @param depotId
     * @param mId
     * @param stock
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertCurrentStockByMaterialAndDepot(String depotId, String mId, BigDecimal stock){
        MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
        materialCurrentStock.setId(IdUtils.getUUID());
        materialCurrentStock.setDepotId(depotId);
        materialCurrentStock.setMaterialId(mId);
        materialCurrentStock.setCurrentNumber(stock);
        materialCurrentStock.setUploadFlag("0");
        materialCurrentStockMapper.insertSelective(materialCurrentStock); //存入初始库存
    }

    /**
     * 批量删除初始库存
     * @param mIdList
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void batchDeleteInitialStockByMaterialList(List<String> mIdList){
        MaterialInitialStockExample example = new MaterialInitialStockExample();
        example.createCriteria().andMaterialIdIn(mIdList);
        materialInitialStockMapper.deleteByExample(example);
    }

    /**
     * 批量删除当前库存
     * @param mIdList
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void batchDeleteCurrentStockByMaterialList(List<String> mIdList){
        MaterialCurrentStockExample example = new MaterialCurrentStockExample();
        example.createCriteria().andMaterialIdIn(mIdList);
        materialCurrentStockMapper.deleteByExample(example);
    }

    public List<MaterialVo4Unit> getMaterialEnableSerialNumberList(String q, Integer offset, Integer rows)throws Exception {
        List<MaterialVo4Unit> list =null;
        try{
            list=  materialMapperEx.getMaterialEnableSerialNumberList(q, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public String getMaterialEnableSerialNumberCount(String q)throws Exception {
        String count =null;
        try{
            count=  materialMapperEx.getMaterialEnableSerialNumberCount(q);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return count;
    }

    public BigDecimal parseBigDecimalEx(String str) throws Exception{
        if(!StringUtil.isEmpty(str)) {
            return  new BigDecimal(str);
        } else {
            return null;
        }
    }

    public BigDecimal parsePrice(String price, String ratio) throws Exception{
        if(StringUtil.isEmpty(price) || StringUtil.isEmpty(ratio)) {
            return null;
        } else {
            BigDecimal pr=new BigDecimal(price);
            BigDecimal r=new BigDecimal(ratio);
            return pr.divide(r,2,BigDecimal.ROUND_HALF_UP);
        }
    }

    /**
     * 根据商品获取初始库存-多仓库
     * @param depotList
     * @param materialId
     * @return
     */
    public BigDecimal getInitStockByMidAndDepotList(List<String> depotList, String materialId) {
        BigDecimal stock = BigDecimal.ZERO;
        MaterialInitialStockExample example = new MaterialInitialStockExample();
        if(depotList!=null && depotList.size()>0) {
            example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdIn(depotList)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        } else {
            example.createCriteria().andMaterialIdEqualTo(materialId)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        }
        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            for(MaterialInitialStock ms: list) {
                if(ms!=null) {
                    stock = stock.add(ms.getNumber());
                }
            }
        }
        return stock;
    }

    /**
     * 根据商品和仓库获取初始库存
     * @param materialId
     * @param depotId
     * @return
     */
    public BigDecimal getInitStock(String materialId, String depotId) {
        BigDecimal stock = BigDecimal.ZERO;
        MaterialInitialStockExample example = new MaterialInitialStockExample();
        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            stock = list.get(0).getNumber();
        }
        return stock;
    }


    /**
     * 根据商品和仓库获取当前库存
     * @param materialId
     * @param depotId
     * @return
     */
    public BigDecimal getCurrentStockByMaterialIdAndDepotId(String materialId, String depotId) {
        BigDecimal stock = BigDecimal.ZERO;
        MaterialCurrentStockExample example = new MaterialCurrentStockExample();
        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<MaterialCurrentStock> list = materialCurrentStockMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            stock = list.get(0).getCurrentNumber();
        } else {
            stock = getInitStock(materialId,depotId);
        }
        return stock;
    }

    /**
     * 根据商品列表获取当前库存Map
     * @param list
     * @return
     */
    public Map<String,BigDecimal> getCurrentStockMapByMaterialList(List<MaterialVo4Unit> list,String depotId) throws Exception {
        Map<String,BigDecimal> map = new HashMap<>();
        List<String> materialIdList = new ArrayList<>();
        for(MaterialVo4Unit materialVo4Unit: list) {
            materialIdList.add(materialVo4Unit.getId());
        }
        String depotIds=null;
        if (StringUtil.isNotEmpty(depotId)){
            depotIds=depotId;
        }else {
            depotIds = depotService.findDepotStrByCurrentUser();
        }
        String[] depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdList(materialIdList,depotArray);
        for(MaterialCurrentStock materialCurrentStock: mcsList) {
            map.put(materialCurrentStock.getMaterialId(), materialCurrentStock.getCurrentNumber());
        }
        return map;
    }

    public Map<String,BigDecimal> getCurrentStockMapByIdListWithTenantId(List<MaterialVo4Unit> list,String depotId) throws Exception {
        Map<String,BigDecimal> map = new HashMap<>();
        List<String> materialIdList = new ArrayList<>();
        for(MaterialVo4Unit materialVo4Unit: list) {
            materialIdList.add(materialVo4Unit.getId());
        }
        String tenantId =null;
        String depotIds=null;
        if (StringUtil.isNotEmpty(depotId)){
            depotIds=depotId;
            tenantId = depotService.getDepotByIdNotTenantId(depotId);
        }else {
            depotIds = depotService.findDepotStrByCurrentUser();

        }
        String[] depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdListWithTenantId(materialIdList,depotArray,tenantId);
        for(MaterialCurrentStock materialCurrentStock: mcsList) {
            map.put(materialCurrentStock.getMaterialId(), materialCurrentStock.getCurrentNumber());
        }
        return map;
    }

    /**
    * @Author: wy
    * @Description: 根据商品id列表获取当前库存
    * @DateTime: 2023-05-08 11:42
    * @Params:
    * @Return
    */
    public Map<String,BigDecimal> getCurrentStockMapByMaterialIdList(List<String> idList,String depotId) throws Exception {
        Map<String,BigDecimal> map = new HashMap<>();
        String depotIds=null;
        if (StringUtil.isNotEmpty(depotId)){
            depotIds=depotId;
        }else {
            depotIds = depotService.findDepotStrByCurrentUser();
        }
        String[] depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdList(idList,depotArray);
        for(MaterialCurrentStock materialCurrentStock: mcsList) {
            map.put(materialCurrentStock.getMaterialId(), materialCurrentStock.getCurrentNumber());
        }
        return map;
    }

    /**
    * @Author: wy
    * @Description: 商品id获取当前库存
    * @DateTime: 2023-05-09 14:40
    * @Params:
    * @Return
    */
    public BigDecimal getCurrentStockMapByMaterialId(String id,String depotId) throws Exception {
        BigDecimal stock =BigDecimal.ZERO;
        String depotIds=null;
        List<String> materialIdList = StringUtil.strToStringList(id);
        if (StringUtil.isNotEmpty(depotId)){
            depotIds=depotId;
        }else {
            depotIds = depotService.findDepotStrByCurrentUser();
        }
        String[] depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdList(materialIdList,depotArray);
        if (mcsList!=null && mcsList.size()>0){
            stock=mcsList.get(0).getCurrentNumber();
        }
        return stock;
    }
    /**
     * 根据商品和仓库获取安全库存信息
     * @param materialId
     * @param depotId
     * @return
     */
    public MaterialInitialStock getSafeStock(String materialId, String depotId) {
        MaterialInitialStock materialInitialStock = new MaterialInitialStock();
        MaterialInitialStockExample example = new MaterialInitialStockExample();
        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            materialInitialStock = list.get(0);
        }
        return materialInitialStock;
    }

    public List<MaterialVo4Unit> getMaterialByMeId(String meId) {
        List<MaterialVo4Unit> result = new ArrayList<MaterialVo4Unit>();
        try{
            if(meId!=null) {
                result= materialMapperEx.getMaterialByMeId(meId);
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public String getMaxBarCode() {
        String maxBarCodeOld = materialMapperEx.getMaxBarCode();
        if(StringUtil.isNotEmpty(maxBarCodeOld)) {
            return Long.parseLong(maxBarCodeOld)+"";
        } else {
            return "1000";
        }
    }

    public List<String> getMaterialNameList() {
        return materialMapperEx.getMaterialNameList();
    }

    public List<MaterialVo4Unit> getMaterialByMeIdList(String meId) {
        String [] meIdArray=meId.split(",");
        return materialMapperEx.getMaterialByMeIdList(meIdArray);
    }

//    public List<MaterialVo4Unit> getMaterialByMaterialId(String materialId,String prefixNo) {
//        List<MaterialVo4Unit> materialList=new ArrayList<MaterialVo4Unit>();
//        List<String> materialIdList = StringUtil.strToStringList(materialId);
//        Integer type=null;
//        if (prefixNo.equals("CGRK")||prefixNo.equals("CGDD")||prefixNo.equals("QCKC")||prefixNo.equals("YHSQ")||prefixNo.equals("XDCG")||prefixNo.equals("XSTH")||prefixNo.equals("QTRK")){
//            type=1;
//        }else if (prefixNo.equals("CGTH")||prefixNo.equals("CJZF")||prefixNo.equals("CJDH")||prefixNo.equals("PSD")||prefixNo.equals("XSDD")||prefixNo.equals("XSCK")||prefixNo.equals("QTCK")){
//            type=2;
//        }else {
//            type=3;
//        }
//        //查询是否有默认出入库单位
//        List<String> extendMaterialId = materialMapperEx.getExtendByMaterialId(materialIdList, type);
//        if (extendMaterialId.size()>0){
//            for (String  material:extendMaterialId){
//                if (materialIdList.contains(material)) {
//                    materialIdList.remove(material);
//                }
//            }
//            materialList = materialMapperEx.getMaterialByMaterialId(extendMaterialId, type);
//        }
//        if (materialIdList.size()>0){
//            List<MaterialVo4Unit>  materialList1 = materialMapperEx.getMaterialByMaterialId(materialIdList, 3   );
//            if (materialList1.size()>0){
//                materialList.addAll(materialList1);
//            }
//        }
//
//        return materialList;
//    }
    public List<MaterialVo4Unit> getMaterialByMaterialId(String materialId,HttpServletRequest request,String lanCode) throws Exception {
        List<String> materialIdList = StringUtil.strToStringList(materialId);
//        String token = request.getHeader("X-Access-Token");
//        String tenantId = Tools.getTenantIdByToken(token);
        String unitFlag =null;
//        SystemConfig systemConfig = synchronizationTaskMapperEx.getSystemConfigByTenantId(tenantId);
//        if (StringUtils.isEmpty(systemConfig.getUnitFlag()) || "0".equals(systemConfig.getUnitFlag())){
//            throw new BusinessRunTimeException(ExceptionConstants.SYSTEM_CONFIG_UNIT_FLAG_EMPTY_CODE,
//                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.SYSTEM_CONFIG_UNIT_FLAG_EMPTY_MSG : ExceptionConstants.SYSTEM_CONFIG_UNIT_FLAG_EMPTY_MSG_US));
//        }else {
//            unitFlag=systemConfig.getUnitFlag();
//        }
        List<MaterialVo4Unit> materialVo4UnitList = null;
        try {
            materialVo4UnitList = materialMapperEx.getMaterialByMaterialId(materialIdList,unitFlag);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return materialVo4UnitList;
    }

    public MaterialVo4Unit getMByMeId(String meId) {
        return materialMapperEx.getMByMeId(meId);
    }


    public List<MaterialInitialStockWithMaterial> getInitialStockWithMaterial(List<String> depotList,List<String> tenantIdList) {
        return synchronizationTaskMapperEx.getInitialStockWithMaterial(depotList,tenantIdList);
    }

    public List<MaterialVo4Unit> getListWithStock(List<String> depotList, List<String> idList, String materialParam, Integer zeroStock,
                                                  String column, String order, Integer offset, Integer rows,List<String> tenantIdList) {
        return synchronizationTaskMapperEx.getListWithStock(depotList, idList, materialParam, zeroStock, column, order, offset, rows,tenantIdList);
    }

    public int getListWithStockCount(List<String> depotList, List<String> idList, String materialParam, Integer zeroStock,List<String> tenantIdList) {
        return synchronizationTaskMapperEx.getListWithStockCount(depotList, idList, materialParam, zeroStock,tenantIdList);
    }

    public List<String> getTenantIdListByDepotIdList(List<String> depotList) {
        return synchronizationTaskMapperEx.getTenantIdListByDepotIdList(depotList);
    }

    public MaterialVo4Unit getTotalStockAndPrice(List<String> depotList, List<String> idList, String materialParam,List<String> tenantIdList) {
        return synchronizationTaskMapperEx.getTotalStockAndPrice(depotList, idList, materialParam,tenantIdList);
    }

    /**
     * 构造扩展信息
     * @param mpArr
     * @param m
     * @return
     */
    public String getMaterialOtherByParam(String[] mpArr, MaterialVo4Unit m) {
        String materialOther = "";
        for (int i = 0; i < mpArr.length; i++) {
            if (mpArr[i].equals("自定义1")) {
                materialOther = materialOther + ((m.getOtherField1() == null || m.getOtherField1().equals("")) ? "" : "(" + m.getOtherField1() + ")");
            }
            if (mpArr[i].equals("自定义2")) {
                materialOther = materialOther + ((m.getOtherField2() == null || m.getOtherField2().equals("")) ? "" : "(" + m.getOtherField2() + ")");
            }
            if (mpArr[i].equals("自定义3")) {
                materialOther = materialOther + ((m.getOtherField3() == null || m.getOtherField3().equals("")) ? "" : "(" + m.getOtherField3() + ")");
            }
        }
        return materialOther;
    }

//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public int batchSetMaterialCurrentStock(String ids) throws Exception {
//        int res = 0;
//        List<String> idList = StringUtil.strToStringList(ids);
//        List<Depot> depotList = depotService.getAllList();
//        for(String mId: idList) {
//            for(Depot depot: depotList) {
//                depotItemService.updateCurrentStockFun(mId, depot.getId());
//                res = 1;
//            }
//        }
//        return res;
//    }

    public int batchUpdate(JSONObject jsonObject) {
        String ids = jsonObject.getString("ids");
        String materialStr = jsonObject.getString("material");
        List<String> idList = StringUtil.strToStringList(ids);
        Material material = JSONObject.parseObject(materialStr, Material.class);
        material.setUploadFlag("0");
        MaterialExample example = new MaterialExample();
        example.createCriteria().andIdIn(idList).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        return materialMapper.updateByExampleSelective(material, example);
    }

    /**
    * @Author: wy
    * @Description: 根据供应商分组
    * @DateTime: 2022/8/6 14:49
    * @Params:
    * @Return
    */
    public String getOrganIdByMaterialId(String id){
       return materialMapperEx.getOrganIdByMaterialId(id);
    }

    public List<PosMaterialVo> posMaterialList(){
        return materialMapperEx.posMaterialList();
    }

    public List<PosMaterialVo> posSaleMaterialList(){
        return materialMapperEx.posSaleMaterialList();
    }

    public StringBuilder notIdList(String id){
        StringBuilder materialNameStr= new StringBuilder();
        MaterialExample example = new MaterialExample();
        example.createCriteria().andIdEqualTo(id);
        List<Material> materials = materialMapper.selectByExample(example);
        for (Material material : materials){
            materialNameStr.append(material.getName());
        }
        return materialNameStr;
    }

    public MaterialVo4Unit getMaterialInfoByBarCode(String barCode) {

        return materialMapperEx.getMaterialInfoByBarCode(barCode);
    }

    public MaterialVo4Unit getMaterialInfoByMaterialNameWithUnit(String materialName,String categoryId,String unit,String standard,String color,String barCode) {

        return materialMapperEx.getMaterialInfoByMaterialNameWithUnit(materialName,categoryId,unit,standard,color,barCode);
    }
    public Material getMaterialInfoByName(String name) {
    MaterialExample example = new MaterialExample();
    example.createCriteria().andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
    List<Material> materials = materialMapper.selectByExample(example);
    if (materials !=null && materials.size() > 0) {
        return materials.get(0);
    }
        return null;
    }
    public List<String> getMaterialIdList() {
        List<String> str = null;
        try{
            str =  materialMapperEx.getMaterialIdList();
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return str;
    }


    public void checkIsMaterialIdList(List<Material> materialList)throws Exception {
        List<Material> list = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        StringBuilder msg= new StringBuilder();
        String lanCode = systemConfigService.getLanCode();
        try{
            if (null!=materialList && materialList.size()>0) {
                for (Material material : materialList) {
                    idList.add(material.getId());
                }
            }
            MaterialExample example = new MaterialExample();
            example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);

            list = materialMapper.selectByExample(example);
            if (null!=list && list.size()>0){
                for (Material m : list){
                    idList.remove(m.getId());
                }
            }
            if (null!=materialList && materialList.size()>0) {
                for (Material material : materialList) {
                    if (idList.contains(material.getId())) {
                        msg.append(material.getName()).append(",");
                    }
                }
            }
            if (idList.size() > 0) {
                Msg msgVo = new Msg();
                msgVo.setId(IdUtils.getUUID());
                msgVo.setMsgTitle("zh".equals(lanCode) ?"新商品提醒" : "New Product Reminder");
                msgVo.setMsgContent("zh".equals(lanCode) ?"总仓有新增商品"+msg.toString()+"请您及时更新":"There is a new product"+msg.toString()+" in the main warehouse, please update it in time");
                msgVo.setCreateTime(new Date());
                msgVo.setType("zh".equals(lanCode) ?"新商品" :"new commodity");
                msgVo.setStatus("1");
                msgVo.setUploadFlag("0");
                msgMapper.insertSelective(msgVo);
            }
        }catch(Exception e){
            JshException.readFail(logger, e,lanCode);
        }
    }

    public  List<SingleItemInventoryVo> singleItemInventory(String code){
        return materialMapperEx.singleItemInventory(code);
    }

    public List<BalanceMaterialVo> balanceMaterialList(String pricing_method, String keyword, String person1, String person2, String person3, Integer page, Integer limit) {
        return  materialMapperEx.balanceMaterialList(pricing_method,keyword,person1,person2,person3,page,limit);
    }

    public Map<String, Object> updatePluCode(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        String lanCode = systemConfigService.getLanCode();
        if(StringUtils.isNotEmpty(jsonObject.getString("goods_id")) && StringUtils.isNotEmpty(jsonObject.getString("plu_code"))){
            MaterialExtend materialExtend = materialExtendMapper.selectByPrimaryKey(jsonObject.getString("goods_id"));
            materialExtend.setSku(jsonObject.getString("plu_code"));
            materialExtend.setUploadFlag("0");
            materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
            map.put("status",1);
            map.put("message","zh".equals(lanCode) ? "修改成功":"success");
        }else {
            map.put("status",0);
            map.put("message","zh".equals(lanCode) ? "参数不足":"Insufficient parameters");
        }
        return map;
    }

    public Map<String, Object> goodsSort(String id) {
        Map<String, Object> map = new HashMap<>();
        String lanCode = systemConfigService.getLanCode();
        List<Map<String, Object>> data =  materialMapperEx.goodsSort(id);
        map.put("data",data);
        map.put("status",1);
        map.put("message","zh".equals(lanCode) ? "查询成功":"success");
        return map;
    }

    public void batchUpdatePrice(BatchUpdatePriceVo vo) {
        List<String> idList = StringUtil.strToStringList(vo.getIds());
        MaterialExtendExample materialExtendExample = new MaterialExtendExample();
        materialExtendExample.createCriteria().andMaterialIdIn(idList).andDeleteFlagEqualTo("0");
        List<MaterialExtend> materialExtendList = materialExtendMapper.selectByExample(materialExtendExample);
        for (MaterialExtend materialExtend : materialExtendList) {
            MaterialExtend newMaterialExtend = new MaterialExtend();
            newMaterialExtend.setId(materialExtend.getId());
            BigDecimal purchaseDecimal = BigDecimal.ZERO;
            boolean b = false;
            if (StringUtils.isNotEmpty(vo.getPurchaseDecimalFormula()) && !vo.getPurchaseDecimalFormula().equals("0")){
                switch (vo.getPurchaseDecimalFormula()) {
                    case "1":
                        purchaseDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        purchaseDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        purchaseDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        purchaseDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        purchaseDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        purchaseDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        purchaseDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        purchaseDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(purchaseDecimal!=null){
                    switch (vo.getPurchaseDecimalOperator()){
                        case "1":
                            newMaterialExtend.setPurchaseDecimal(purchaseDecimal.add(vo.getPurchaseDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(purchaseDecimal.subtract(vo.getPurchaseDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(purchaseDecimal.multiply(vo.getPurchaseDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(purchaseDecimal.divide(vo.getPurchaseDecimal(),BigDecimal.ROUND_UP,2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal commodityDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getCommodityDecimalFormula()) && !vo.getCommodityDecimalFormula().equals("0")){
                switch (vo.getCommodityDecimalFormula()) {
                    case "1":
                        commodityDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        commodityDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        commodityDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        commodityDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        commodityDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        commodityDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        commodityDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        commodityDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(commodityDecimal!=null) {
                    switch (vo.getCommodityDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(commodityDecimal.add(vo.getCommodityDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(commodityDecimal.subtract(vo.getCommodityDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(commodityDecimal.multiply(vo.getCommodityDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(commodityDecimal.divide(vo.getCommodityDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal lowDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getLowDecimalFormula()) && !vo.getLowDecimalFormula().equals("0")){
                switch (vo.getLowDecimalFormula()) {
                    case "1":
                        lowDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        lowDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        lowDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        lowDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        lowDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        lowDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        lowDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        lowDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(lowDecimal!=null) {
                    switch (vo.getLowDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(lowDecimal.add(vo.getLowDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(lowDecimal.subtract(vo.getLowDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(lowDecimal.multiply(vo.getLowDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(lowDecimal.divide(vo.getLowDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal wholesaleDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getWholesaleDecimalFormula()) && !vo.getWholesaleDecimalFormula().equals("0")){
                switch (vo.getWholesaleDecimalFormula()) {
                    case "1":
                        wholesaleDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        wholesaleDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        wholesaleDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        wholesaleDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        wholesaleDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        wholesaleDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        wholesaleDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        wholesaleDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(wholesaleDecimal!=null) {
                    switch (vo.getWholesaleDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(wholesaleDecimal.add(vo.getWholesaleDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(wholesaleDecimal.subtract(vo.getWholesaleDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(wholesaleDecimal.multiply(vo.getWholesaleDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(wholesaleDecimal.divide(vo.getWholesaleDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal twoWholesaleDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getTwoWholesaleDecimalFormula()) && !vo.getTwoWholesaleDecimalFormula().equals("0")){
                switch (vo.getTwoWholesaleDecimalFormula()) {
                    case "1":
                        twoWholesaleDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        twoWholesaleDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        twoWholesaleDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        twoWholesaleDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        twoWholesaleDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        twoWholesaleDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        twoWholesaleDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        twoWholesaleDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(twoWholesaleDecimal!=null) {
                    switch (vo.getTwoWholesaleDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(twoWholesaleDecimal.add(vo.getTwoWholesaleDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(twoWholesaleDecimal.subtract(vo.getTwoWholesaleDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(twoWholesaleDecimal.multiply(vo.getTwoWholesaleDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(twoWholesaleDecimal.divide(vo.getTwoWholesaleDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal threeWholesaleDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getThreeWholesaleDecimalFormula()) && !vo.getThreeWholesaleDecimalFormula().equals("0")){
                switch (vo.getThreeWholesaleDecimalFormula()) {
                    case "1":
                        threeWholesaleDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        threeWholesaleDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        threeWholesaleDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        threeWholesaleDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        threeWholesaleDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        threeWholesaleDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        threeWholesaleDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        threeWholesaleDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(threeWholesaleDecimal!=null) {
                    switch (vo.getThreeWholesaleDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(threeWholesaleDecimal.add(vo.getThreeWholesaleDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(threeWholesaleDecimal.subtract(vo.getThreeWholesaleDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(threeWholesaleDecimal.multiply(vo.getThreeWholesaleDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(threeWholesaleDecimal.divide(vo.getThreeWholesaleDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal fourWholesaleDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getFourWholesaleDecimalFormula()) && !vo.getFourWholesaleDecimalFormula().equals("0")){
                switch (vo.getFourWholesaleDecimalFormula()) {
                    case "1":
                        fourWholesaleDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        fourWholesaleDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        fourWholesaleDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        fourWholesaleDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        fourWholesaleDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        fourWholesaleDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        fourWholesaleDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        fourWholesaleDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(fourWholesaleDecimal!=null) {
                    switch (vo.getFourWholesaleDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(fourWholesaleDecimal.add(vo.getFourWholesaleDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(fourWholesaleDecimal.subtract(vo.getFourWholesaleDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(fourWholesaleDecimal.multiply(vo.getFourWholesaleDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(fourWholesaleDecimal.divide(vo.getFourWholesaleDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            BigDecimal fiveWholesaleDecimal = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(vo.getFiveWholesaleDecimalFormula()) && !vo.getFiveWholesaleDecimalFormula().equals("0")){
                switch (vo.getFiveWholesaleDecimalFormula()) {
                    case "1":
                        fiveWholesaleDecimal = materialExtend.getPurchaseDecimal();
                        break;
                    case "2":
                        fiveWholesaleDecimal = materialExtend.getCommodityDecimal();
                        break;
                    case "3":
                        fiveWholesaleDecimal = materialExtend.getLowDecimal();
                        break;
                    case "4":
                        fiveWholesaleDecimal = materialExtend.getWholesaleDecimal();
                        break;
                    case "5":
                        fiveWholesaleDecimal = materialExtend.getTwoWholesaleDecimal();
                        break;
                    case "6":
                        fiveWholesaleDecimal = materialExtend.getThreeWholesaleDecimal();
                        break;
                    case "7":
                        fiveWholesaleDecimal = materialExtend.getFourWholesaleDecimal();
                        break;
                    case "8":
                        fiveWholesaleDecimal = materialExtend.getFiveWholesaleDecimal();
                        break;
                    default:
                        break;
                }
                if(fiveWholesaleDecimal!=null) {
                    switch (vo.getFiveWholesaleDecimalOperator()) {
                        case "1":
                            newMaterialExtend.setCommodityDecimal(fiveWholesaleDecimal.add(vo.getFiveWholesaleDecimal()));
                            b=true;
                            break;
                        case "2":
                            newMaterialExtend.setPurchaseDecimal(fiveWholesaleDecimal.subtract(vo.getFiveWholesaleDecimal()));
                            b=true;
                            break;
                        case "3":
                            newMaterialExtend.setPurchaseDecimal(fiveWholesaleDecimal.multiply(vo.getFiveWholesaleDecimal()));
                            b=true;
                            break;
                        case "4":
                            newMaterialExtend.setPurchaseDecimal(fiveWholesaleDecimal.divide(vo.getFiveWholesaleDecimal(), BigDecimal.ROUND_UP, 2));
                            b=true;
                            break;
                        default:
                            break;
                    }
                }
            }
            if(b){
                materialExtendMapper.updateByPrimaryKeySelective(newMaterialExtend);
            }
        }
    }

    public String selectMinimumUnit(String color) {
        return materialMapperEx.selectMinimumUnit(color);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetMaterialTenant(String ids,String syncTenantId) throws Exception {
        int result =0;
        List<String> idList = StringUtil.strToStringList(ids);
        MaterialExample example=new MaterialExample();
        example.createCriteria().andIdIn(idList);
        Material material=new Material();
        material.setSyncTenantId(syncTenantId);
        try{
//            if (idList != null && idList.size()>0){
//                for (String id :idList){
//                    List<String> tenantIdList = StringUtil.strToStringList(syncTenantId);
//                    if (tenantIdList != null && tenantIdList.size()>0){
//                        for (String tenantId :tenantIdList){
//                            int count = materialMapperEx.findMaterialBySyncTenantId(id, tenantId);
//                            if (count > 0){
//
//                            }else {
//
//                            }
//                        }
//                    }
//
//                }
//            }
            result=  materialMapper.updateByExampleSelective(material, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public Map<String, Object> batchUpdateStock(JSONObject jsonObject) {
//        Map<String, Object> map = new HashMap<>();
//        List<Depot> depotList =null;
//        try {
//            depotList = depotService.getDepot();
//            if (depotList != null && depotList.size()>0){
//                List<String> idList = depotList.stream().map(Depot::getId).collect(Collectors.toList());
//                MaterialCurrentStockExample example=new MaterialCurrentStockExample();
//                example.createCriteria().andDepotIdNotIn(idList);
//                MaterialCurrentStock materialCurrentStock=new MaterialCurrentStock();
//                materialCurrentStock.setUploadFlag("0");
//                materialCurrentStock.setDeleteFlag("1");
//                materialCurrentStockMapper.updateByExampleSelective(materialCurrentStock,example);
//
//                List<Material> materialList = getMaterial();
//                for (Depot depot:depotList){
//                    if (materialList !=null && materialList.size()>0){
//                        for (Material material :materialList){
//                            depotItemService.updateCurrentStockFun(material.getId(),depot.getId());
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
//        return map;
//    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> batchUpdateStock(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        try {
            Person person = personService.selectPerson("updateStock");
            if (person != null ) {
                String beginTime = Tools.getCenternTime(person.getCreateTime());
                String endTime = Tools.getNow3();
                List<DepotItem> depotItemList = depotItemService.getStockCountDetailList(beginTime, endTime);
                if (depotItemList !=null && depotItemList.size()>0){
                    List<MaterialCurrentStock> stockList =new ArrayList<>();
                    for (DepotItem depotItem : depotItemList){
                        String materialId = depotItem.getMaterialId();
                        String depotId = depotItem.getDepotId();
                        CashBoxRecord record = cashBoxRecordMapperEx.selectByMaterialId(materialId,depotId);
                        if (record != null){
                            List<String> depotList = new ArrayList<>();
                            depotList.add(depotId);
                            BigDecimal updateStock = depotItemService.getStockByParamWithDepotList(depotList, materialId, beginTime, endTime);
                            if (record.getEditMoney() != null){
                                record.setEditMoney(record.getEditMoney().add(updateStock));
                            }else {
                                record.setEditMoney(updateStock);
                            }
                            MaterialCurrentStock stock =new MaterialCurrentStock();
                            stock.setId(record.getRecordId());
                            stock.setCurrentNumber(record.getEditMoney());
                            stock.setUploadFlag("0");
                            stockList.add(stock);
                        }
                    }
                    if (stockList.size()>0){
                        materialCurrentStockMapperEx.updateMaterialCurrentStockList(stockList);
                    }
                }
                person.setType("1");
                personMapper.updateByPrimaryKeySelective(person);

                Person saveStockPerson = personService.selectPerson("saveStock");
                saveStockPerson.setType("1");
                personMapper.updateByPrimaryKeySelective(saveStockPerson);
            }else {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
                        "Please complete the save stock");
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> saveStockHistory(JSONObject jsonObject) throws Exception{
        Map<String, Object> map = new HashMap<>();
        List<Depot> depotList =null;
        Person person = personService.selectPerson("updateStock");
        if (person != null && !"1".equals(person.getType())){
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
                    "Please complete the stock count");
        }
        try {
            Date date = new Date();
            depotList = depotService.getDepot();
            if (depotList != null && depotList.size()>0){
                List<String> idList = depotList.stream().map(Depot::getId).collect(Collectors.toList());
                MaterialCurrentStockExample example=new MaterialCurrentStockExample();
                example.createCriteria().andDepotIdNotIn(idList);
                MaterialCurrentStock materialCurrentStock=new MaterialCurrentStock();
                materialCurrentStock.setUploadFlag("0");
                materialCurrentStock.setDeleteFlag("1");
                materialCurrentStockMapper.updateByExampleSelective(materialCurrentStock,example);

                cashBoxRecordMapper.deleteByExample(new CashBoxRecordExample());

                List<CashBoxRecord> recordList = new ArrayList<>();
                MaterialCurrentStockExample stockExample=new MaterialCurrentStockExample();
                stockExample.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                List<MaterialCurrentStock> materialCurrentStocks = materialCurrentStockMapper.selectByExample(stockExample);
                if (materialCurrentStocks != null && materialCurrentStocks.size()>0){
                    for (MaterialCurrentStock stock : materialCurrentStocks){
                        CashBoxRecord record = new CashBoxRecord();
                        record.setId(IdUtils.getUUID());
                        record.setRecordId(stock.getId());
                        record.setEditMoney(stock.getCurrentNumber());
                        record.setAddTime(date);
                        recordList.add(record);
                    }
                    cashBoxRecordMapperEx.insertList(recordList);
                }
                Person person1 = new Person();
                person1.setId(IdUtils.getUUID());
                person1.setName("updateStock");
                person1.setType("0");
                person1.setCreateTime(date);
                person1.setUpdateTime(date);
                personMapper.insertSelective(person1);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return map;
    }
}
